"use client";

import {
  PageContainer,
  ProCard,
  ProForm,
  ProFormTextArea,
  ProFormSelect,
} from "@ant-design/pro-components";
import { Button, Space, Divider, Row, Col, Input, Upload } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { useState } from "react";
import { useMessage } from "../../hooks/useMessage";

interface BannerItem {
  id: string;
  image: string;
  link: string;
}

interface InstrumentOption {
  label: string;
  value: string;
}

const HomeManagementPage: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [pushLoading, setPushLoading] = useState(false);
  const [banners, setBanners] = useState<BannerItem[]>([
    { id: "1", image: "", link: "" },
    { id: "2", image: "", link: "" },
    { id: "3", image: "", link: "" },
  ]);
  const [instruments] = useState<InstrumentOption[]>([
    { label: "扫描电子显微镜", value: "1" },
    { label: "透射电子显微镜", value: "2" },
    { label: "X射线衍射仪", value: "3" },
    { label: "原子力显微镜", value: "4" },
    { label: "红外光谱仪", value: "5" },
    { label: "拉曼光谱仪", value: "6" },
    { label: "核磁共振波谱仪", value: "7" },
    { label: "质谱仪", value: "8" },
    { label: "色谱仪", value: "9" },
    { label: "光电子能谱仪", value: "10" },
  ]);
  const message = useMessage();

  const handleSave = async (values: Record<string, unknown>) => {
    setLoading(true);
    try {
      // 收集推荐仪器
      const recommendedInstruments = [
        values.instrument1,
        values.instrument2,
        values.instrument3,
        values.instrument4,
        values.instrument5,
        values.instrument6,
        values.instrument7,
        values.instrument8,
      ].filter(Boolean);

      const config = {
        banners: banners.map((banner, index) => ({
          id: banner.id,
          image: banner.image,
          link: banner.link,
          order: index + 1,
        })),
        recommendedInstruments,
        notification: values.notification || "",
        consultQrCode: values.consultQrCode || "",
        financeQrCode: values.financeQrCode || "",
      };

      // TODO: 调用API保存首页配置
      console.log("保存首页配置:", config);
      message.success("更新成功");
    } catch (error) {
      console.error("保存失败:", error);
      message.error("保存失败");
    } finally {
      setLoading(false);
    }
  };

  const handleGlobalPush = async (notification: string) => {
    if (!notification) {
      message.error("请输入通知内容");
      return;
    }

    setPushLoading(true);
    try {
      // TODO: 调用API进行全局推送
      console.log("全局推送:", notification);
      message.success("推送成功");
    } catch (error) {
      console.error("推送失败:", error);
      message.error("推送失败");
    } finally {
      setPushLoading(false);
    }
  };

  const handleBannerLinkChange = (index: number, link: string) => {
    const newBanners = [...banners];
    newBanners[index].link = link;
    setBanners(newBanners);
  };

  const handleBannerImageChange = (index: number, url: string) => {
    const newBanners = [...banners];
    newBanners[index].image = url;
    setBanners(newBanners);
  };

  const [consultQrCode, setConsultQrCode] = useState<string>("");
  const [financeQrCode, setFinanceQrCode] = useState<string>("");

  return (
    <PageContainer
      title="首页管理"
      content="管理首页展示内容，包括轮播图、推荐仪器、通知公告等"
    >
      <ProCard>
        <ProForm
          onFinish={handleSave}
          submitter={{
            render: (props) => (
              <Space>
                <Button
                  type="primary"
                  loading={loading}
                  onClick={() => props.form?.submit?.()}
                >
                  保存配置
                </Button>
                <Button onClick={() => props.form?.resetFields?.()}>
                  重置
                </Button>
              </Space>
            ),
          }}
        >
          {/* Banner配置 */}
          <ProCard title="banner配置" bordered headerBordered>
            <div style={{ marginBottom: 16 }}>
              <Row gutter={[16, 16]}>
                {banners.map((banner, index) => (
                  <Col span={8} key={banner.id}>
                    <div className="border border-gray-200 rounded-lg p-4">
                      <div className="text-sm font-medium mb-2">
                        首页banner{index + 1}:
                      </div>
                      <Upload
                        className="mb-2"
                        name="file"
                        action="/api/upload"
                        listType="picture-card"
                        showUploadList={false}
                        onChange={(info) => {
                          if (info.file.status === "done") {
                            // 假设返回的数据结构包含url
                            handleBannerImageChange(
                              index,
                              info.file.response?.url || ""
                            );
                          }
                        }}
                      >
                        {banner.image ? (
                          <img
                            src={banner.image}
                            alt={`banner${index + 1}`}
                            style={{
                              width: "100%",
                              height: "100%",
                              objectFit: "cover",
                            }}
                          />
                        ) : (
                          <div className="text-center text-gray-500">
                            <PlusOutlined className="text-2xl mb-2" />
                            <div>点击上传图片</div>
                          </div>
                        )}
                      </Upload>
                      <Input
                        placeholder="请输入"
                        value={banner.link}
                        onChange={(e) =>
                          handleBannerLinkChange(index, e.target.value)
                        }
                        addonBefore={`首页banner${index + 1}跳转链接:`}
                      />
                    </div>
                  </Col>
                ))}
              </Row>
            </div>
          </ProCard>

          <Divider />

          {/* 推荐仪器配置 */}
          <ProCard title="推荐仪器配置" bordered headerBordered>
            <Row gutter={[16, 16]}>
              <Col span={6}>
                <ProFormSelect
                  name="instrument1"
                  label="首页展示仪器1:"
                  placeholder="请选择仪器"
                  options={instruments}
                />
              </Col>
              <Col span={6}>
                <ProFormSelect
                  name="instrument2"
                  label="首页展示仪器2:"
                  placeholder="请选择仪器"
                  options={instruments}
                />
              </Col>
              <Col span={6}>
                <ProFormSelect
                  name="instrument3"
                  label="首页展示仪器3:"
                  placeholder="请选择仪器"
                  options={instruments}
                />
              </Col>
              <Col span={6}>
                <ProFormSelect
                  name="instrument4"
                  label="首页展示仪器4:"
                  placeholder="请选择仪器"
                  options={instruments}
                />
              </Col>
            </Row>
            <Row gutter={[16, 16]} style={{ marginTop: 16 }}>
              <Col span={6}>
                <ProFormSelect
                  name="instrument5"
                  label="首页展示仪器5:"
                  placeholder="请选择仪器"
                  options={instruments}
                />
              </Col>
              <Col span={6}>
                <ProFormSelect
                  name="instrument6"
                  label="首页展示仪器6:"
                  placeholder="请选择仪器"
                  options={instruments}
                />
              </Col>
              <Col span={6}>
                <ProFormSelect
                  name="instrument7"
                  label="首页展示仪器7:"
                  placeholder="请选择仪器"
                  options={instruments}
                />
              </Col>
              <Col span={6}>
                <ProFormSelect
                  name="instrument8"
                  label="首页展示仪器8:"
                  placeholder="请选择仪器"
                  options={instruments}
                />
              </Col>
            </Row>
          </ProCard>

          <Divider />

          {/* 通知配置 */}
          <ProCard title="通知配置" bordered headerBordered>
            <ProFormTextArea
              name="notification"
              label="首页通知:"
              placeholder="请输入"
              fieldProps={{
                rows: 3,
              }}
              extra="更新后展示在首页"
            />
            <div style={{ marginTop: 16 }}>
              <Button
                type="default"
                loading={pushLoading}
                onClick={() => {
                  // 获取表单当前值
                  const formElement = document.querySelector(
                    'textarea[id*="notification"]'
                  ) as HTMLTextAreaElement;
                  if (formElement) {
                    handleGlobalPush(formElement.value);
                  }
                }}
              >
                推送
              </Button>
              <span style={{ marginLeft: 8, color: "#666" }}>
                全局推送，主动推送消息
              </span>
            </div>
          </ProCard>

          <Divider />

          {/* 咨询二维码 */}
          <ProCard title="咨询二维码" bordered headerBordered>
            <Row gutter={[32, 16]}>
              <Col span={12}>
                <div>
                  <div className="text-sm font-medium mb-2">
                    全局咨询二维码:
                  </div>
                  <Upload
                    name="file"
                    action="/api/upload"
                    listType="picture-card"
                    showUploadList={false}
                    onChange={(info) => {
                      if (info.file.status === "done") {
                        setConsultQrCode(info.file.response?.url || "");
                      }
                    }}
                  >
                    {consultQrCode ? (
                      <img
                        src={consultQrCode}
                        alt="全局咨询二维码"
                        style={{
                          width: "100%",
                          height: "100%",
                          objectFit: "cover",
                        }}
                      />
                    ) : (
                      <div className="text-center text-gray-500">
                        <PlusOutlined className="text-xl mb-1" />
                        <div className="text-xs">点击上传图片</div>
                      </div>
                    )}
                  </Upload>
                </div>
              </Col>
              <Col span={12}>
                <div>
                  <div className="text-sm font-medium mb-2">财务二维码:</div>
                  <Upload
                    name="file"
                    action="/api/upload"
                    listType="picture-card"
                    showUploadList={false}
                    onChange={(info) => {
                      if (info.file.status === "done") {
                        setFinanceQrCode(info.file.response?.url || "");
                      }
                    }}
                  >
                    {financeQrCode ? (
                      <img
                        src={financeQrCode}
                        alt="财务二维码"
                        style={{
                          width: "100%",
                          height: "100%",
                          objectFit: "cover",
                        }}
                      />
                    ) : (
                      <div className="text-center text-gray-500">
                        <PlusOutlined className="text-xl mb-1" />
                        <div className="text-xs">点击上传图片</div>
                      </div>
                    )}
                  </Upload>
                </div>
              </Col>
            </Row>
          </ProCard>
        </ProForm>
      </ProCard>
    </PageContainer>
  );
};

export default HomeManagementPage;
